# 功能：合并cookie购物车到redis
# 参数：request请求对象用于获取cookies购物车数据，　response响应对象对象用于请求cookie购物车,删除购物车

from meiduo_mall.utils.cookiesecret import CookieSecret
from django_redis import get_redis_connection
import json

def merge_cart_cookie_to_redis(request, response):
    """
    登录后合并cookie购物车数据到Redis
    :param request: 本次请求对象，获取cookie中的数据
    :param response: 本次响应对象，清除cookie中的数据
    :return: response
    """
    # 提取cookie购物车数据
    cookie_str = request.COOKIES.get('carts')
    if cookie_str:

        cart_dict = CookieSecret.loads(cookie_str)
    else:
        cart_dict = {}

    # 把cookie购物车数据合并到redis中
    redis_conn = get_redis_connection('carts')
    # 商品数量
    # 不用hincryby()--这个是累加进去，要用hset()
    # 选中状态
    # sadd(), srem(),直接插入去除，不会抛异常
    user = request.user
    sku_ids = cart_dict.keys()
    for sku_id in sku_ids:
        redis_conn.hset('carts_%s'%user.id, sku_id, cart_dict[sku_id]['count'])
        selected = cart_dict[sku_id]['selected']
        if selected:
            redis_conn.sadd('selected_%s'%user.id, sku_id)
        else:
            redis_conn.srem('selected_%s'%user.id, sku_id)
        # redis_conn.hset(request.id, sku_id, json.dumps(cookie_dict[sku_id]))
    # 删除cookie
    response.delete_cookie('carts')













